var MutationObserver = window.MutationObserver || window.WebkitMutationObserver || window.MozMutationObserver;
var danmuObserver = null;

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
      console.log(sender.tab ?
                  "from a content script:" + sender.tab.url :
                  "from the extension");
      if (request.danmuTask == "startObserve")
        startObserve(request.myNickName);
      else if(request.danmuTask == "stopObserve")
        stopObserve(request.myNickName); 
    });

//监听页面弹幕变化
//var targetNode = document.getElementsByClassName('danmu-6e95c1')[0];

/**  开始监控节点 */
function startObserve(myNickName){
   console.log('============nickName contains',myNickName,'observe start============');
  //options：监听的属性
  var options = { attributes: true, childList: true,subtree:true,attributeOldValue:true};
  //回调事件
  function callback(mutationsList, observer) {
      // console.log(mutationsList);
      mutationsList.forEach(element => {
        //   console.log(element);
          if(element.addedNodes.length>0){
              var $_addNode = $(element.addedNodes);
              var findNickName = $_addNode.find('.Barrage-nickName.js-nick').attr('title');
              if(findNickName && findNickName.indexOf(myNickName)!=-1){
                  console.log($($_addNode).find('.Barrage-content').text());
                  notify(findNickName,$($_addNode).find('.Barrage-content').text());
                //   alert($($_addNode).find('.Barrage-content').text());     
              }
          }
      });
      
  }

  danmuObserver = new MutationObserver(callback);
  // 通过屏幕弹幕没有监听到是否是超管的办法,尝试按右边的聊天框判断
  var sourceDanmuNode = document.getElementById('js-barrage-list');
  console.log('start danmuObserve:',sourceDanmuNode);
  danmuObserver.observe(sourceDanmuNode, options);
}

/** 停止节点监控 */
function stopObserve(myNickName){
  danmuObserver.disconnect();
  danmuObserver = null;
  console.log('============nickName contains',myNickName,'observe end============');
}

function notify(noticeName,noticeContent) {
  if (!('Notification' in window)) {
      alert('你的浏览器不支持Notification');
  }//检查是否拥有通知权限；有就通知，没有请求；
  else if (Notification.permission=='granted') {
    var options={
      body : noticeContent,
      icon : 'images/get_started48.png',
      sound:audioNotification(),
      tag : {} // 可以加一个tag
  };
    var notification=new Notification(noticeName,options);
  }else if (Notification.permission !== 'denied'){
      Notification.requestPermission(
        function(permission){
          console.log('permission:',permission);
            if (permission=='granted'){
                var notification=new Notification('hello wolrld!');
            }
        }
    );
  }
}

function audioNotification(){
  var yourSound = new Audio('http://df.notf.com/a.mp3');
  yourSound.play();
}